import 'dart:io';

import 'package:flutter/material.dart';
import 'package:flutter_changdian_football/api/api_response.dart';
import 'package:flutter_changdian_football/api/req/club/req_club.dart';
import 'package:flutter_changdian_football/api/req/court/req_court.dart';
import 'package:flutter_changdian_football/api/req/other/req_other.dart';
import 'package:flutter_changdian_football/model/club/club_avatar_model.dart';
import 'package:flutter_changdian_football/routers/app_routes.dart';
import 'package:flutter_changdian_football/utils/custom_constant.dart';
import 'package:flutter_changdian_football/utils/custom_logger.dart';
import 'package:flutter_changdian_football/utils/custom_toast.dart';
import 'package:flutter_changdian_football/utils/event/custom_event_util.dart';
import 'package:flutter_changdian_football/utils/image_compress_util.dart';
import 'package:flutter_changdian_football/widget/dialog/operational_results_dialog.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:flutter_pickers/address_picker/locations_data.dart';
import 'package:get/get.dart';
import 'package:image_picker/image_picker.dart';
import 'package:dio/dio.dart' as dio;

class CreateClubController extends GetxController {

  List jjqdList = [
    {
      'key': 'HEALTH_FOOTBALL',
      'value': '养身足球'
    },
    {
      'key': 'MEDIUM_STRENGTH',
      'value': '中等强度'
    },
    {
      'key': 'FIERCE_CONFRONTATION',
      'value': '激烈对抗'
    },
    {
      'key': 'UNCERTAIN',
      'value': '不确定'
    },
  ];

  List<String> jjqdStrList = [
    '养身足球', '中等强度', '激烈对抗', '不确定'
  ];

  int selectJjqdIndex = -1;

  changeSelectJjqdIndex(p) {
    selectJjqdIndex = p;
    clubSportsName = jjqdList[p]['value'];
    clubSportsValue = jjqdList[p]['key'];
    update();
  }






  String? clubSportsName;
  String? clubSportsValue;

  String? province1;
  String? city1;

  String? clubAddress;
  String? clubHomeCourtName;

  changeAddress(province, city, district) async {
    EasyLoading.show();
    province1 = province;
    city1 = city;

    List<String> codeList = Address.getCityCodeByName(provinceName: province, cityName: city, townName: district);
    clubAddress = '$province $city';
    clubRegionCode = codeList[1];
    await getCourtList(codeList[1]);
  }

  List courtList = [];
  List<String> courtStrList = [];
  int selectCourtIndex = -1;
  changeSelectCourtIndex(p) {
    selectCourtIndex = p;
    clubHomeCourtName = courtStrList[p];
    update();
  }

  getCourtList(regionCode) async {
    var resp = await ReqCourt.courtList(regionCode);
    if (resp.status == Status.completed) {
      if (resp.data['code'] == '200') {
        courtList.clear();
        courtStrList.clear();
        selectCourtIndex = -1;

        courtList.addAll(resp.data['data']);
        for (int i = 0; i < courtList.length; i++) {
          courtStrList.add('${courtList[i]['courtName']}');
        }
        update();
      }
    }
  }

  String? clubRegionCode;

  TextEditingController clubNameController = TextEditingController();
  TextEditingController clubProfileController = TextEditingController();

  /// 新增俱乐部
  addClub() async {
    FocusScope.of(Get.context!).requestFocus(FocusNode());
    if (clubImage == null) {
      CustomToast.showTextToast('请设置俱乐部徽章头像');
      return ;
    }

    if (clubNameController.text.trim() == '') {
      CustomToast.showTextToast('请设置俱乐部名称');
      return ;
    }

    if (clubAddress == null) {
      CustomToast.showTextToast('请选择俱乐部所在地');
      return ;
    }

    if (clubHomeCourtName == null) {
      CustomToast.showTextToast('请选择活动主场');
      return ;
    }

    if (selectJjqdIndex == -1) {
      CustomToast.showTextToast('请选择竞技强度');
      return ;
    }

    if (clubProfileController.text.trim() == '') {
      CustomToast.showTextToast('请设置俱乐部简介');
      return ;
    }
    try {
      EasyLoading.show();
      var resp = await ReqClub.addClub(
        clubAddress: '${clubAddress ?? ''}',
        clubHomeCourtId: '${courtList[selectCourtIndex]['courtId']}',
        clubHomeCourtName: clubHomeCourtName ?? '',
        clubImage: clubImage ?? '',
        clubName: clubNameController.text,
        clubProfile: clubProfileController.text,
        clubSportsValue: clubSportsValue ?? '',
        clubRegionCode: clubRegionCode ?? ''
      );

      if (resp.data['code'] == '200') {
        OperationalResultsDialog.show(
          Get.context!,
          text: '创建俱乐部成功',
          icon: 'assets/images/img_tc_cg.png',
          confirmTap: () {
            Get.until((route) => Get.currentRoute == AppRoutes.main);
            eventBus.fire(const BottomNavigationBarEvent(CustomConstant.EVENT_CLUB_REFRESH));
          }
        );
      } else {
        OperationalResultsDialog.show(
          Get.context!,
          text: resp.data['msg'],
          icon: 'assets/images/img_tc_sb.png',
          confirmTap: () {
            Get.back();
          }
        );
      }
    } catch (e) {
      logger.d(e);
      OperationalResultsDialog.show(
        Get.context!,
        text: '创建俱乐部失败',
        icon: 'assets/images/img_tc_sb.png',
        confirmTap: () {
          Get.back();
        }
      );
    } finally {
      EasyLoading.dismiss();
    }
  }



  String? clubImage;




  photoSelectImage() async {
    Get.back();
    final PickedFile? image = await ImagePicker().getImage(source: ImageSource.gallery);

    if (image != null) {
      addImage(image.path);
    }
  }

  shootSelectImage() async {
    Get.back();
    final PickedFile? photo = await ImagePicker().getImage(source: ImageSource.camera);
    if (photo != null) {
      addImage(photo.path);
    }
  }

  addImage(path) async {
    try {
      EasyLoading.show();
      File imageCompressedImage = await ImageCompressUtil().imageCompressAndGetFile(File(path));

      dio.FormData formData = dio.FormData.fromMap(
        {
          'file': await dio.MultipartFile.fromFile(imageCompressedImage.path),
          'businessType': 'CLUB_AVATAR'
        }
      );
      var resp = await ReqOther.fileUpload(formData);
      if (resp.status == Status.completed) {
        if (resp.data['code'] == '200') {
          clubImage = resp.data["data"];
          update();
        } else {
          CustomToast.showTextToast(resp.data['msg']);
        }
      } else {
        CustomToast.showTextToast('系统繁忙，请稍后再试！');
      }
    } catch (e) {
      CustomToast.showTextToast('系统繁忙，请稍后再试！');
    } finally {
      EasyLoading.dismiss();
    }
  }


  @override
  void onInit() {
    super.onInit();

    defaultClubAvatar();
  }

  List<DefaultClubAvatarModel> defaultClubAvatarList = [];

  defaultClubAvatar() async {
    var resp = await ReqOther.defaultClubAvatar();
    if (resp.status == Status.completed) {
      if (resp.data['code'] == '200') {
        for (int i = 0; i < resp.data['data'].length; i++) {
          defaultClubAvatarList.add(DefaultClubAvatarModel.fromJson(resp.data['data'][i]));
        }
      } 
    }
  }

}